package com.geostar.constructionland.attachment.service.impl;

import com.geostar.constructionland.attachment.entity.RepEntity;
import com.geostar.constructionland.attachment.service.IStorageService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * @author : yell
 * @Description: FastDFS存储实现
 * @date : 2020/01/02 11:09
 */
@Service(value = "fastDFSStorageService")
public class FastDFSStorageServiceImpl implements IStorageService {
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    public void setFastFileStorageClient(FastFileStorageClient fastFileStorageClient) {
        this.fastFileStorageClient = fastFileStorageClient;
    }


    @Override
    public RepEntity uploadAttach(byte[] attachBytes,long attachSize,String fileName,String fileExt) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(attachBytes);
        String fileExtStr = StringUtils.isNotEmpty(fileExt)?fileExt:FilenameUtils.getExtension(fileName);
        StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, attachSize, fileExtStr,null);
        return new RepEntity("200",storePath.getFullPath());
    }

    @Override
    public byte[] getByteArrayByFilePath(String filePath) {
        String group = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }


    @Override
    public boolean deleteAttachById(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
        return true;
    }
}
